package pw.goyd.game.handler.imp;

import org.jboss.netty.channel.ChannelHandlerContext;
import pw.goyd.db.RedisUtil;
import pw.goyd.game.api.DBDone;
import pw.goyd.game.api.Utils;
import pw.goyd.game.constant.setting.GameSetting;
import pw.goyd.game.handler.Handler;
import pw.goyd.game.logic.LoginRequest;
import pw.goyd.game.logic.MessageBoxResponse;
import pw.goyd.game.logic.PlayerInfoResponse;
import pw.goyd.game.manager.GameManager;
import pw.goyd.game.model.Account;
import pw.goyd.game.model.Player;
import pw.goyd.game.server.Log;
import pw.goyd.game.server.LoginList;
import pw.goyd.protocol.model.Response;
import pw.goyd.subscribe.BinaryRedisPubSubListener;
import pw.goyd.subscribe.PlayerCustomer;
import redis.clients.jedis.Jedis;

public class LOGIN extends Handler {
    /**
     * 登录
     */
    @Override
    public void handle() {

        LoginRequest loginRequest = new LoginRequest();
        loginRequest.readFromBytes(request.getData());
        // System.out.println("Login---->" + loginRequest.getAccount());
        String acc = loginRequest.getAccount();
        String pwd = loginRequest.getPassword();

        // Check PWD
        if (DBDone.check(acc, pwd)) {
            Log.getLogger().debug("Login---->" + "账号" + acc);
            if (!LoginList.isAccountExist(acc)) {
                sendLogin(ctx, acc);
            } else if (GameSetting.FORCELOGIN) {
                // 1.发送给下线方
                MessageBoxResponse msgBox = new MessageBoxResponse();
                msgBox.setCode((byte) 1);// 回到登录界面
                msgBox.setMessage("您的账号已在其他设备登录！");
                Response loseRes = new Response();
                loseRes.setData(msgBox.getBytes());
                loseRes.setCmd(CMD_MSGBOX);

                LoginList.getPlayer(acc).getChannel().write(loseRes);
                LoginList.removePlayer(acc);

                // 2.给当前登录目标
                // 账号存在 就强制登录
                sendLogin(ctx, acc);
            } else {
                // 不允许强制登录
                MessageBoxResponse msgBox = new MessageBoxResponse();
                msgBox.setCode((byte) 1);// 回到登录界面
                msgBox.setMessage("该账号已在其他设备登录！");
                Response loseRes = new Response();
                loseRes.setData(msgBox.getBytes());
                loseRes.setCmd(CMD_MSGBOX);
                ctx.getChannel().write(loseRes);
            }
        } else {
            MessageBoxResponse msgBox = new MessageBoxResponse();
            msgBox.setCode((byte) 0);
            msgBox.setMessage("账号密码不匹配！");
            Response loseRes = new Response();
            loseRes.setData(msgBox.getBytes());
            loseRes.setCmd(CMD_MSGBOX);
            ctx.getChannel().write(loseRes);
        }

    }

    /**
     * 发送登录信息 加入账号 上线下线账号合并
     *
     * @param ctx context
     * @param acc 账号
     */
    private void sendLogin(ChannelHandlerContext ctx, String acc) {
        PlayerCustomer player = LoginList.getPlayer(acc);
        if (player == null) {    //	无在线缓存
            Player p = DBDone.getPlayer(acc);
            if (p == null || p.getNickname().isEmpty()) {
                //新建玩家对象 nickname为空
                p = new Player(DBDone.getAccount(acc).getAccount_id());
            }
            player = p.toCustomer();
        } else {
            //TODO 只更新了部分信息
            Player p = DBDone.getPlayer(acc);        //	获取最新数据
            if (p != null) {
                player.setNickname(p.getNickname());
                player.setDiamond(p.getDiamond());
                player.setIcon_source(p.getIcon_source());
                player.setGold(p.getGold());
                player.setAd_count(p.getAd_count());
                player.setLucky_count(p.getLucky_count());
            }
        }


        // 回个人信息
        PlayerInfoResponse playerInfoResponse = new PlayerInfoResponse();
        playerInfoResponse.setPlayer(player);

        Response info = new Response();
        info.setCmd(CMD_PLAYERINFO);
        info.setData(playerInfoResponse.getBytes());
        info.setTime(0);
        ctx.getChannel().write(info);

        // Observer订阅频道
        // 新建一个Listener 为redisclient监听订阅
        BinaryRedisPubSubListener listener = new BinaryRedisPubSubListener();
        if (player.getJedis() != null)             //  回收上次登录jedis客户端
            RedisUtil.returnResource(player.getJedis());
        Jedis client = RedisUtil.getJedis();    //  从池中获取
        player.setJedis(client);
        player.setRoomID(-1);                   //  当前不在房间
        player.setBinaryRedisPubSubListener(listener);
        player.setChannel(ctx.getChannel());
        player.psub();

        listener.setSub(player);
        if (!LoginList.addPlayer(acc, player))
            Log.getLogger().info("ListAdd---->error 账号:" + acc);
        //Log.getLogger().info("订阅---->全局订阅 账号:" + acc + " 玩家:" + player.getNickname());


        //更新account
        String ip = ctx.getChannel().getRemoteAddress().toString();
        Account account = DBDone.getAccount(acc);
        account.setLast_login_ip(ip);
        account.setLast_login_time(Utils.getCurrentTime());
        DBDone.setAccount(account);

        if (account.getAccount_type().equals("2")) {
            GameManager.sendAnnounceMsg("欢迎尊贵的VIP玩家 [" + player.getNickname() + "] 进入游戏");
        }
    }

}
